<template>
	<div class="components-image-libs">
		<div class="image-lib-side-bar"></div>
		<el-tabs tab-position="top" v-model="imgtype" @tab-click="setType">
			<!-- <el-tab-pane label="背景图片" name="1">背景图片</el-tab-pane> -->
			<!-- <el-tab-pane label="组件图片" name="2">组件图片</el-tab-pane>
			<el-tab-pane label="地图底图" name="3">地图底图</el-tab-pane>
			<el-tab-pane label="装饰图片" name="4">装饰图片</el-tab-pane>
			<el-tab-pane label="未分组" name="0">未分组</el-tab-pane> -->
		</el-tabs>

		<div class="image-lib-inner">
			<div class="image-lib-btn">
				<el-upload :before-upload="beforeUpload" :show-file-list="false" accept="jpg, png, gif" action="/">
					<el-button size="small" type="primary"
						>点击上传图片
						<!-- {{
							{
								"1": "背景图片",
								"2": "组件图片",
								"3": "地图底图",
								"4": "装饰图片",
								"0": "不分组图片",
							}[imgtype]
						}} -->
					</el-button>
					<span class="el-upload__tip marginL20" slot="tip">只能上传jpg/png/gif文件，且不超过1M</span>
				</el-upload>
			</div>
			<ul class="image-list-wrapper" v-if="imageList.length">
				<li :key="index" @click="handleImageClick(item.url)" class="image-item" v-for="(item, index) in imageList">
					<img :src="item.url" alt />
					<div class="delstyle"><i class="el-icon-delete" @click.stop="delimg(item._id)"></i></div>
				</li>
			</ul>
			<div class="padding60 text-center gray" v-else>暂无数据</div>
		</div>
	</div>
</template>

<script>
const OSS = require('ali-oss')
export default {
	name: 'ImgLibs',
	data() {
		return {
			uploading: false,
			hasLoadData: false,
			imageList: [],
			selectId: '',
			imgtype: '1',
			ossimgurl: 'https://img.zczy56.com/',
		}
	},
	props: {
		unique: String,
	},
	created() {
		this.$bus.$on('show-select-image', selectId => {
			this.selectId = selectId
		})
		this.getMyImages()
	},
	watch: {
		dialogVisible(val) {
			//
			if (val && !this.uploading) {
				this.getMyImages()
			}
		},
	},
	methods: {
		beforeUpload(file) {
			if (file.size > 1 * 1024 * 1024) {
				this.$message.error('psd文件不能超过1M')
				return
			}
			let temp1 = file.name.split('.')
			let temp = temp1[temp1.length - 1]
			if (!['jpg', 'png', 'gif'].includes(temp)) {
				this.$message.error('请上传jpg/png/gif文件')
				return false
			}
			this.uploadPsd(file)
			return false
		},
		uploadPsd(file) {
			const client = new OSS({
				// yourRegion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
				//region: "oss-cn-shanghai.aliyuncs.com",
				// 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
				accessKeyId: 'LTAI4FfzVCCkJgM3C4TvR1Wh',
				accessKeySecret: 'XVUJUA2YpHXDwCznqHQMlOtmCcHCwW',
				endpoint: 'oss-cn-shanghai.aliyuncs.com',
				bucket: 'zczy',
				//expiration: 10,
				// 刷新临时访问凭证的时间间隔，单位为毫秒。
				//refreshSTSTokenInterval: 300000,
				// 填写Bucket名称。
			})

			const upload = async () => {
				try {
					this.uploading = true
					client
						.multipartUpload('base-dir/' + Date.parse(new Date()) + file.name, file)
						.then(res => {
							if (res.name) {
								this.$axios
									.post('/person/updateImage', {
										url: this.ossimgurl + res.name,
										type: this.imgtype,
									})
									.then(noderes => {
										console.log(noderes)
										this.uploading = false
										this.getMyImages()
										this.$message.success('图片上传成功')
									})
									.catch(err => {
										this.$message.error('图片上传失败：' + err)
									})
							} else {
								this.$message.error('图片上传失败')
							}
						})
						.catch(err => {
							this.$message.error('图片上传失败：' + err)
						})
				} catch (e) {
					console.error('报错：', e)
				}
			}
			upload()
		},

		uploadPsd1(file) {
			let params = new FormData()
			params.append('file', file)
			params.append('type', this.imgtype)
			this.uploading = true
			this.$axios
				.post('http://192.168.88.38:4000/person/uploadImage', params)
				.then(res => {
					this.uploading = false
					this.imageList.splice(0, 0, res.body)
				})
				.catch(() => {
					this.uploading = false
				})
		},
		getMyImages() {
			this.hasLoadData = true
			//this.$axios.get("http://192.168.88.38:4000/person/images", { type: this.imgtype }).then((res) => {
			this.$axios.get('/person/images', { type: this.imgtype }).then(res => {
				this.imageList = res.body || []
			})
		},
		delimg(id) {
			//console.log('2')
			this.$axios.post('/person/delImages', { id }).then(res => {
				if (res.code == 200) {
					this.getMyImages()
				}
			})
		},
		handleImageClick(url) {
			console.log('1', this.unique)
			this.$bus.$emit('select-image', this.selectId, url, this.unique)
		},
		setType() {
			this.getMyImages()
		},
	},
}
</script>

<style lang="scss" scoped>
.image-list-wrapper {
	display: flex;
	flex-wrap: wrap;
	height: 400px;
	min-width: 650px;
	padding-top: 20px;
	.image-item {
		width: 120px;
		height: 120px;
		background: #eee 50% / contain no-repeat;
		cursor: pointer;
		justify-content: center;
		align-items: center;
		display: flex;
		transition: all 0.28s;
		margin-left: 10px;
		margin-top: 10px;
		position: relative;
		&:hover {
			box-shadow: 0 0 16px 0 rgba(0, 0, 0, 0.16);
			transform: translate3d(0, -2px, 0);
		}
		img {
			display: inline-block;
			max-width: 100%;
			max-height: 100%;
		}
		.delstyle {
			position: absolute;
			right: 10px;
			bottom: 5px;
			color: #000;
			font-size: 14px;
			// color: rgba($color: #0004ff, $alpha: 1.0);
			z-index: 1;
		}
	}
}
</style>
<style lang="stylus">
.dialog-body_wrap {
	padding-top: 0;
}
</style>
